package org.redmagic.extractor;

import java.util.HashSet;
import java.util.Set;

/**
 * 
 * @author Sean Dobberstein
 *
 */
public class ExtractorImpl implements Extractor {

    private static final String PLACEHOLDER_PREFIX = "${";
    private static final String PLACEHOLDER_SUFFIX = "}";
    private static final int PREFIX_LENGTH = PLACEHOLDER_PREFIX.length();
    
    public ExtractorImpl() {
        
    }
    
    @Override
    public Set<String> extract(String input) {
        Set<String> properties = new HashSet<String>();
        int startIndex = input.indexOf(PLACEHOLDER_PREFIX);
        int endIndex = input.indexOf(PLACEHOLDER_SUFFIX, startIndex);
        
        while (startIndex > -1 && endIndex > -1) {
            int nextStartIndex = input.indexOf(PLACEHOLDER_PREFIX, startIndex + PREFIX_LENGTH);
            
            if (nextStartIndex == -1 || nextStartIndex > endIndex) {
                String placeholder = input.substring(startIndex + PREFIX_LENGTH, endIndex);
                properties.add(placeholder);
                startIndex = nextStartIndex;
                endIndex = input.indexOf(PLACEHOLDER_SUFFIX, startIndex);
            } else {
                startIndex = nextStartIndex;
            }
        }
        
        return properties;
    }
}